package com.xxtx.trade.thread;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.xxtx.trade.agent.dto.ImeiToPhoneDto;
import com.xxtx.trade.agent.mapper.TradeSysAgentMapper;
import com.xxtx.trade.common.enums.ExportEnum;
import com.xxtx.trade.common.util.cache.CacheManager;
import com.xxtx.trade.common.util.springUtil.SpringUtil;
import com.xxtx.trade.fieldManage.dto.FieldManageDto;
import com.xxtx.trade.fieldManage.mapper.FieldManageMapper;
import com.xxtx.trade.sysUser.bean.UrlInfosKuaiShou;
import com.xxtx.trade.sysUser.dto.KuaiShouInfoDto;
import lombok.Data;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Data
public class DownloadKuaiShouInfoThread implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(DownloadAdminSimThread.class);

    private int count;
    private String url;
    private String id; // 每次下载时随机出的 id

    private String userId; // 用户id
//    private String agentId; // 这个可以用来在info表中查询

    //    private String role_id; // 用户角色，管理员与普通用户
    private int type; //1

    private KuaiShouInfoDto kuaiShouInfoDto;

    @Override
    public void run() {
        Integer pageCount = count / 100000 + 1;
        TradeSysAgentMapper tradeSysAgentMapper = SpringUtil.getBean(TradeSysAgentMapper.class);
        CacheManager cacheManager = SpringUtil.getBean(CacheManager.class);
        FieldManageMapper fieldManageMapper = SpringUtil.getBean(FieldManageMapper.class);

        // 一次性把 imei 和 phone 对照表查询出来，不用查询那么多次
        List<ImeiToPhoneDto> imeiToPhoneDtos = tradeSysAgentMapper.selectImeiList();
        HashMap<String, String> map = new HashMap<>();
        for (ImeiToPhoneDto imeiToPhoneDto : imeiToPhoneDtos) {
            map.put(imeiToPhoneDto.getImei(), imeiToPhoneDto.getPhone());
        }

        Map<String, Object> hashMap = new HashMap<>();

        Workbook workbook = null;

        ExportParams params = new ExportParams();

        try {
            if (type == 1) {
                List<UrlInfosKuaiShou> users = null;
                // 查询，每次查询10W条数据
                for (int i = 1; i <= pageCount; i++) {
                    kuaiShouInfoDto.setPageNo((i - 1) * 100000);
                    if (i == pageCount) {
                        kuaiShouInfoDto.setPerPageNum(count % 100000);
                    } else {
                        kuaiShouInfoDto.setPerPageNum(100000);
                    }

                    //按用户权限查询
                    users = tradeSysAgentMapper.selectExcelUrlInfosKuaiShou(kuaiShouInfoDto);
                    // 给user 插入place字段
                    for (UrlInfosKuaiShou urlInfosKuaiShou : users) {
                        if (urlInfosKuaiShou.getPhone() == null) continue;
                        Collection<Object> phone_list = new ArrayList<>();
                        phone_list.add(urlInfosKuaiShou.getPhone().substring(0, 7));
                        String aa = (String) cacheManager.hMGet("phoneOwnership2", phone_list).get(0);
                        if (aa == null) {
                            urlInfosKuaiShou.setPlace("未入库地区");
                            continue;
                        }
                        urlInfosKuaiShou.setPlace(aa.split("_")[1]);
                    }
                    if (kuaiShouInfoDto.getUser_role().equals("2")) {
                        workbook = ExcelExportUtil.exportBigExcel(params, UrlInfosKuaiShou.class, users);
                        users.clear();
                    } else {
                        // 生成要导出的数据
                        List<Map<String, String>> resultList = new ArrayList<>();
                        // 生成导出的列名
                        List<ExcelExportEntity> entityList = new ArrayList<>();

                        // ExcelExportEntity agentNameEntity = new ExcelExportEntity("客户名称", "agentName");
                        // entityList.add(agentNameEntity);

                        // 查询可显示字段，创建列名
                        List<FieldManageDto> fieldManageDtos = fieldManageMapper.getList();
                        for (FieldManageDto fieldManageDto : fieldManageDtos) {
                            if (fieldManageDto.getStatus().equals("1")) {
                                if (fieldManageDto.getSource().equals("7")) {
                                    ExcelExportEntity ele = new ExcelExportEntity(fieldManageDto.getName(), fieldManageDto.getName());
                                    entityList.add(ele);
                                }
                            }
                        }
                        // 装载数据
                        for (UrlInfosKuaiShou urlInfosKuaiShou : users) {
                            Map<String, String> rowMap = new HashMap<>();
                            for (ExcelExportEntity excelExportEntity : entityList) {
                                if (excelExportEntity.getKey().equals("agentName")) {
                                    rowMap.put("agentName", urlInfosKuaiShou.getAgentName());
                                }
                                if (excelExportEntity.getKey().equals("urlName")) {
                                    rowMap.put("urlName", urlInfosKuaiShou.getUrlName());
                                }
                                if (excelExportEntity.getKey().equals("idfaMD5")) {
                                    rowMap.put("idfaMD5", urlInfosKuaiShou.getIdfaMD5());
                                }
                                if (excelExportEntity.getKey().equals("phone")) {
                                    rowMap.put("phone", urlInfosKuaiShou.getPhone());
                                }
                                if (excelExportEntity.getKey().equals("place")) {
                                    rowMap.put("place", urlInfosKuaiShou.getPlace());
                                }
                                if (excelExportEntity.getKey().equals("imeiMD5")) {
                                    rowMap.put("imeiMD5", urlInfosKuaiShou.getImeiMD5());
                                }
                                if (excelExportEntity.getKey().equals("createTime")) {
                                    rowMap.put("createTime", urlInfosKuaiShou.getCreateTime());
                                }
                                if (excelExportEntity.getKey().equals("did")) {
                                    rowMap.put("did", urlInfosKuaiShou.getDid());
                                }
                                if (excelExportEntity.getKey().equals("aid")) {
                                    rowMap.put("aid", urlInfosKuaiShou.getAid());
                                }
                                if (excelExportEntity.getKey().equals("cid")) {
                                    rowMap.put("cid", urlInfosKuaiShou.getCid());
                                }
                                if (excelExportEntity.getKey().equals("dname")) {
                                    rowMap.put("dname", urlInfosKuaiShou.getDname());
                                }
                                if (excelExportEntity.getKey().equals("unitname")) {
                                    rowMap.put("unitname", urlInfosKuaiShou.getUnitname());
                                }
                                if (excelExportEntity.getKey().equals("photoid")) {
                                    rowMap.put("photoid", urlInfosKuaiShou.getPhotoid());
                                }
                                if (excelExportEntity.getKey().equals("oaid2")) {
                                    rowMap.put("oaid2", urlInfosKuaiShou.getOaid2());
                                }
                                if (excelExportEntity.getKey().equals("os")) {
                                    rowMap.put("os", urlInfosKuaiShou.getOs());
                                }
                                if (excelExportEntity.getKey().equals("model")) {
                                    rowMap.put("model", urlInfosKuaiShou.getModel());
                                }
                                if (excelExportEntity.getKey().equals("csite")) {
                                    rowMap.put("csite", urlInfosKuaiShou.getCsite());
                                }
                            }
                            resultList.add(rowMap);
                        }
                        workbook = ExcelExportUtil.exportBigExcel(params, entityList, resultList);
                        resultList.clear();
                        users.clear();
                    }
                }
            }
//            workbook.write(new FileOutputStream("E:/download/" + url));
            workbook.write(new FileOutputStream("/root/develop/export/" + url));
            workbook.close();
            hashMap.put("state", ExportEnum.SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.debug("导出失败信息为" + e.getMessage());
            LOGGER.debug("导出失败信息为" + e.getLocalizedMessage());
            hashMap.put("state", ExportEnum.FAIL.getCode());
        }
        hashMap.put("id", id);
        Date date = new Date();
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String LgTime = sdformat.format(date);
        hashMap.put("endTime", LgTime);
        tradeSysAgentMapper.updateExporeByid(hashMap);

    }


}
